package com.bjpowernode.rbac.service.impl;

import com.bjpowernode.rbac.entity.Role;
import com.bjpowernode.rbac.mapper.RoleMapper;
import com.bjpowernode.rbac.query.QueryObject;
import com.bjpowernode.rbac.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author jy
 * @version 1.0
 * @date 2022/2/8 20:51
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Role> selectAllRoles() {
        return roleMapper.selectAll();
    }

    @Override
    public PageInfo<Role> selectDepartmentByCondition(QueryObject queryObject) {
        PageHelper.startPage(queryObject.getCurrentPage(),queryObject.getPageSize());
        List<Role> list = roleMapper.selectByCondition(queryObject);
        return new PageInfo<>(list);
    }

    @Override
    public void saveOrUpdate(Role role,Long[] permissionIds) {
        Role role1 = roleMapper.selectByPrimaryKey(role.getId());
        if (role.getId() != null || role1 != null){
            roleMapper.updateByPrimaryKeySelective(role);
            //解绑原来的角色--权限表
            roleMapper.deleteRelation(role.getId());
        }else {
            roleMapper.insert(role);
        }

        //重新绑定角色--权限表
        if (permissionIds != null && permissionIds.length > 0){
            for (Long permissionId : permissionIds) {
                roleMapper.addRelation(role.getId(),permissionId);
            }

        }

    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Role selectRoleById(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }
}
